/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sda.levelup.ciphers;

/**
 *
 * @author Дима
 */
public class Vigenere implements Icipher
{

    public String encrypt(String input, String key)
    {
        key = key.toLowerCase();
        Alphabet alpha = new Alphabet();
        String abc = alpha.alphabet();
        String finalKey = "";
        char[] mas = input.toCharArray();
        int start = 0;
        char c = 'a';
        while (finalKey.length() < input.length())
        {
            c = key.charAt(start);
            finalKey += Character.toString(c);
            start++;
            if (start == key.length())
            {
                start = 0;
            }
        }
        for (int i = 0; i < input.length(); i++)
        {

            if (abc.contains(Character.toString(Character.toLowerCase(mas[i]))))
            {
                start = ((abc.indexOf(Character.toLowerCase(mas[i])) + abc.indexOf(finalKey.charAt(i))) % 26);
                c = abc.charAt(start);
                if (Character.getType(mas[i]) == Character.UPPERCASE_LETTER)
                {

                    mas[i] = Character.toUpperCase(c);
                }
                else
                {
                    mas[i] = c;
                }
            }
        }
        String result = new String(mas);
        return result;
    }

    public String decrypt(String input, String key)
    {
        key = key.toLowerCase();
        Alphabet alpha = new Alphabet();
        String abc = alpha.alphabet();
        String finalKey = "";
        char[] mas = input.toCharArray();
        int start = 0;
        char c = 'a';
        while (finalKey.length() < input.length())
        {
            c = key.charAt(start);
            finalKey += Character.toString(c);
            start++;
            if (start == key.length())
            {
                start = 0;
            }
        }
        for (int i = 0; i < input.length(); i++)
        {

            if (abc.contains(Character.toString(Character.toLowerCase(mas[i]))))
            {
                start = ((abc.indexOf(Character.toLowerCase(mas[i])) - abc.indexOf(finalKey.charAt(i)) + 26) % 26);
                c = abc.charAt(start);
                if (Character.getType(mas[i]) == Character.UPPERCASE_LETTER)
                {

                    mas[i] = Character.toUpperCase(c);
                }
                else
                {
                    mas[i] = c;
                }
            }
        }
        String result = new String(mas);
        return result;
    }

}
